package ml.kupin.controller;

import ml.kupin.content.service.ContentCategoryService;
import ml.kupin.common.utils.KuPinResult;
import ml.kupin.common.vo.EasyUITreeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * Created by 小柯(Allen Kerr) on 17.4.26 19:15.
 */
@Controller
@RequestMapping("/content/category")
public class ContentCategoryController {

    @Autowired
    private ContentCategoryService contentCatService;

    /**
     * 获取内容分类树
     *
     * @param parentId
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public List<EasyUITreeNode> getContentCategories(@RequestParam(value = "id", defaultValue = "0") long parentId) {
        List<EasyUITreeNode> treeNodeList = contentCatService.getContentCategories(parentId);
        return treeNodeList;
    }

    /**
     * 在内容分类树上新增节点
     * 链接："/content/category/create"
     * 参数：{parentId:node.parentId,name:node.text}
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public KuPinResult createContentCategory(long parentId, String name) {
        KuPinResult kuPinResult = null;
        try {
            kuPinResult = contentCatService.addContentCategory(parentId, name);
        } catch (Exception e) {
            //捕获异常，添加失败
            e.printStackTrace();
            //返回错误信息
            return KuPinResult.notOk("内容分类添加失败！");
        }
        //添加成功
        return kuPinResult;
    }

    /**
     * 修改内容分类
     * $.post("/content/category/update",{id:node.id,name:node.text});
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public KuPinResult updateContentCategory(long id, String name) {
        KuPinResult kuPinResult = null;
        try {
            kuPinResult = contentCatService.updateContentCategory(id, name);
        } catch (Exception e) {
            e.printStackTrace();
            return KuPinResult.notOk("重命名失败！");
        }
        return kuPinResult;
    }

    /**
     * 删除内容分类
     * —— 只能删除叶子节点，不能删除父节点
     * $.post("/content/category/delete/", {id: node.id}, function (data) {});
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public KuPinResult deleteContentCategory(long id) {
        KuPinResult kuPinResult = null;
        try {
            kuPinResult = contentCatService.deleteContentCategory(id);
        } catch (Exception e) {
            e.printStackTrace();
            return KuPinResult.notOk("节点删除失败！");
        }
        return kuPinResult;
    }

}
